package com.yu.mall.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;

import com.yu.mall.mapStruct.card.CardVOChange;
import com.yu.mall.util.ExcelUtil;
import com.yu.mall.vo.card.CardVolumeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yu.mall.dto.BaseDTO;
import com.yu.mall.dto.PageDTO;
import com.yu.mall.entity.AdminUser;
import com.yu.mall.entity.CardVolume;
import com.yu.mall.entity.User;
import com.yu.mall.mapper.CardVolumeMapper;
import com.yu.mall.mapper.UserMapper;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.PageResultVO;
import com.yu.mall.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@RestController
@RequestMapping("CardVolume")
@Api(tags = "卡卷管理", value = "卡卷管理")
public class CardVolumeController {

	@Autowired
	private CardVolumeMapper cardVolumeMapper;

	@Autowired
	CardVOChange cardVOChange;
	
    @Autowired
    UserMapper userMapper;

	@PostMapping("getCardNum")
	@ApiOperation(value = "生成卡卷")
	@ApiImplicitParams({ @ApiImplicitParam(name = "number", value = "生成数量", dataType = "int",example = "1"),
		 	@ApiImplicitParam(name = "type", value = "0普通  1劳保", dataType = "String"),
			@ApiImplicitParam(name = "amount", value = "卡卷金额", dataType = "String") })
	public ResultVO getCardNum(String amount,String type, int number) {

		if (String.valueOf(number).equals("")) {
			return ResultUtils.error("生成数量不能为空");
		}

		if (amount == null || "".equals(amount)) {
			return ResultUtils.error("卡卷金额不能为空");
		}
		List<CardVolume> createSerialNo = createSerialNo(amount, number);
		for (CardVolume cardVolume : createSerialNo) {
			cardVolume.setIsactivate("1");
			cardVolume.setType(type);
			cardVolumeMapper.insert(cardVolume);
		}
		
		return ResultUtils.success("生成成功!");
	}
	
	@PostMapping("activateCard")
	@ApiOperation(value = "激活卡卷")
	@ApiImplicitParam(name = "cardVolumeNum",value="卡卷号", dataType = "String",required=true)
	public ResultVO activateCard(String cardVolumeNum) {

		if (String.valueOf(cardVolumeNum).equals("")) {
			return ResultUtils.error("卡卷号不能为空");
		}
		String[] split = cardVolumeNum.split(",");

		for (String string : split) {
			Example example = new Example(CardVolume.class);
			Criteria createCriteria = example.createCriteria();
			createCriteria.andEqualTo("cardVolumeNum", string);
			CardVolume selectOneByExample = cardVolumeMapper.selectOneByExample(example);
			if(selectOneByExample !=null) {
				selectOneByExample.setIsactivate("0");
				cardVolumeMapper.updateByPrimaryKey(selectOneByExample);
			}
		}
		return ResultUtils.success("激活成功!");
	}
	
	@PostMapping("delCard")
	@ApiOperation(value = "删除卡卷")
	@ApiImplicitParam(name = "cardVolumeNum",value="卡卷号", dataType = "String",required=true)
	public ResultVO delCard(String cardVolumeNum) {

		if (String.valueOf(cardVolumeNum).equals("")) {
			return ResultUtils.error("卡卷号不能为空");
		}
		String[] split = cardVolumeNum.split(",");

		for (String string : split) {
			Example example = new Example(CardVolume.class);
			Criteria createCriteria = example.createCriteria();
			createCriteria.andEqualTo("cardVolumeNum", string);
			cardVolumeMapper.deleteByExample(example);
		}
		return ResultUtils.success("激活成功!");
	}
	
	@PostMapping("queryCardList")
	@ApiOperation(value = "查询卡卷")
	@ApiImplicitParams({ @ApiImplicitParam(name = "istag", value = "0:失效 1：未失效"),
			@ApiImplicitParam(name = "amount", value = "金额", dataType = "String"),
			@ApiImplicitParam(name = "isexport", value = "0:已导出1：未导出", dataType = "String") })
	public PageResultVO<List<CardVolumeVO>> queryCardList(PageDTO dto,String amount, String istag, String isexport) {
		 Example example = new Example(CardVolume.class);
		 Criteria createCriteria = example.createCriteria();
		 if (StringUtils.isNotBlank(amount)) {
			 createCriteria.andEqualTo("amount", amount);
		 }
		 if (StringUtils.isNotBlank(istag)) {
			 createCriteria.andEqualTo("istag", istag);
		 }
		 if (StringUtils.isNotBlank(isexport)) {
			 createCriteria.andEqualTo("isexport", isexport);
		 }
		 PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
		 List<CardVolume> selectByExample = cardVolumeMapper.selectByExample(example);
		 List<CardVolumeVO> vo = new ArrayList<CardVolumeVO>();
		 for (CardVolume cardVolume : selectByExample) {
			 CardVolumeVO cardVolumeVO = new CardVolumeVO();
			 cardVolumeVO.setCardVolumeNum(cardVolume.getCardVolumeNum());
			 cardVolumeVO.setAmount(cardVolume.getAmount());
			 cardVolumeVO.setIstag(cardVolume.getIstag());
			 cardVolumeVO.setIsexport(cardVolume.getIsexport());
			 cardVolumeVO.setIsactivate(cardVolume.getIsactivate());
			 cardVolumeVO.setOpenid(cardVolume.getOpenid());
			 cardVolumeVO.setType(cardVolume.getType());
			 vo.add(cardVolumeVO);
		}
		 
		 for (CardVolumeVO cardVolumeVO : vo) {
			 if(!"".equals(cardVolumeVO.getOpenid()) && cardVolumeVO.getOpenid() !=null) {
				 User user = userMapper.selectByPrimaryKey(cardVolumeVO.getOpenid());
				 cardVolumeVO.setPhone(user.getPhone());
				 System.out.println("user.getBalance()"+user.getBalance());
				 cardVolumeVO.setBalance(user.getBalance());
			 }
		}
		 PageInfo pageInfo = new PageInfo<>(selectByExample);
		 pageInfo.setList(vo);
	     return ResultUtils.page(pageInfo);
	}
	
	@GetMapping("exportCard")
	@ApiOperation(value = "导出卡卷")
	@ApiImplicitParams({ @ApiImplicitParam(name = "istag", value = "0:失效 1：未失效"),
			@ApiImplicitParam(name = "amount", value = "金额", dataType = "String"),
			@ApiImplicitParam(name = "isexport", value = "0:已导出1：未导出", dataType = "String")})
	public void exportCard(String amount, String istag, String isexport, HttpServletResponse response) throws Exception {
		 Example example = new Example(CardVolume.class);
		 Criteria createCriteria = example.createCriteria();
		 if (StringUtils.isNotBlank(amount)) {
			 createCriteria.andEqualTo("amount", amount);
		 }
		 if (StringUtils.isNotBlank(istag)) {
			 createCriteria.andEqualTo("istag", istag);
		 }
		 if (StringUtils.isNotBlank(isexport)) {
			 createCriteria.andEqualTo("isexport", isexport);
		 }
		 List<CardVolume> selectByExample = cardVolumeMapper.selectByExample(example);
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		 String now = sdf.format(new Date());
		 List<CardVolumeVO> list = cardVOChange.toVo(selectByExample);
		 for (CardVolumeVO cardVolumeVO : list) {
			 if(!"".equals(cardVolumeVO.getOpenid()) && cardVolumeVO.getOpenid() !=null) {
				 User user = userMapper.selectByPrimaryKey(cardVolumeVO.getOpenid());
				 cardVolumeVO.setPhone(user.getPhone());
				 System.out.println("user.getBalance()"+user.getBalance());
				 cardVolumeVO.setBalance(user.getBalance());
			 }
		}
		 ExcelUtil.write("导出卡卷"+now, list, "卡卷信息", CardVolumeVO.class, response);
		 for (CardVolume cardVolume : selectByExample) {
			 CardVolume o = new CardVolume();
			 o.setId(cardVolume.getId());
			 o.setIsexport("0");
			 cardVolumeMapper.updateByPrimaryKeySelective(o);
		}
	}
	
	@GetMapping("balanceTurnAdd")
	@ApiOperation(value = "余额转增")
	@ApiImplicitParams({ @ApiImplicitParam(name = "phone", value = "手机号"),
			@ApiImplicitParam(name = "amount", value = "金额", dataType = "String")})
	public ResultVO balanceTurnAdd(BaseDTO baseDTO,String phone, String amount, HttpServletResponse response) throws Exception {
		 if (!StringUtils.isNotBlank(baseDTO.getOpenid())) {
			 return ResultUtils.error("用户不存在!");
		 }
		 User user = userMapper.selectByPrimaryKey(baseDTO.getOpenid());
		 if(Objects.isNull(user)){
             return ResultUtils.error("用户不存在");
         }
		 if (!StringUtils.isNotBlank(amount)) {
			 return ResultUtils.error("转增金额为空!");
		 }
		 BigDecimal bigDecimal = new BigDecimal(amount);
		 if(user.getBalance().compareTo(bigDecimal) == -1){
			 return ResultUtils.error("转增金额大于余额!");
		 }
		 Example example = new Example(User.class);
		 Criteria createCriteria = example.createCriteria();
		 if (StringUtils.isNotBlank(phone)) {
			 createCriteria.andEqualTo("phone", phone);
		 }else {
			 return ResultUtils.error("手机号为空!");
		 }
		 
		 List<User> selectByExample = userMapper.selectByExample(example);
		 if(selectByExample.size()>0) {
			 BigDecimal balance = selectByExample.get(0).getBalance();
			 BigDecimal add = balance.add(bigDecimal);
			 selectByExample.get(0).setBalance(add);
			 userMapper.updateByPrimaryKey(selectByExample.get(0));
			 user.setBalance(user.getBalance().subtract(bigDecimal));
			 userMapper.updateByPrimaryKey(user);
			 
		 }else {
			 return ResultUtils.error("手机号未查到用户!");
		 }
		 return ResultUtils.success("转增成功!");
	}
	
	/**
	 * 可用多线程检测是否会产生相同随机数
	 * 
	 * @param length
	 * @return
	 */
	public static List<CardVolume> createSerialNo(String amount,int length) {
		ArrayList<CardVolume> arrayList = new ArrayList<CardVolume>();
		SimpleDateFormat sdf = new SimpleDateFormat("MddHHmmss");
		String now = sdf.format(new Date());
		for (int i = 0; i < length; i++) {
			
			String createSerialNo = now + getCharAndNumr3(7);
			CardVolume cardVolume = new CardVolume();
			cardVolume.setAmount(amount);
			cardVolume.setCardVolumeNum(createSerialNo);
			cardVolume.setIstag("1");
			cardVolume.setIsexport("1");
			arrayList.add(cardVolume);
		}
		return arrayList;
		
	}

    public static String getCharAndNumr3(int length) {
        StringBuffer valSb = new StringBuffer();  
        for (int i = 0; i < length; i++) {  
            String charOrNum = Math.round(Math.random()) % 2 == 0 ? "char" : "num"; // 输出字母还是数字  
            if ("char".equalsIgnoreCase(charOrNum)) {  
                // 字符串  
                int choice = Math.round(Math.random()) % 2 == 0 ? 65 : 97;  // 取得大写字母还是小写字母  
                valSb.append((char) (choice + Math.round(Math.random()*25)));  
            } else if ("num".equalsIgnoreCase(charOrNum)) {  
                // 数字  
                valSb.append(String.valueOf(Math.round(Math.random()*9)));  
            }  
        }  
        return valSb.toString();  
    } 
}
